/**
 * 
 */
package org.cuatrovientos.erp.dao;

import java.util.List;

import org.cuatrovientos.erp.model.Sale;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author natalia
 *
 */
public class SaleDAO implements SaleDAOInterface{
	@Autowired
	 private SessionFactory sessionFactory;
	

	/**
	 * default constructor
	 */
	public SaleDAO () {
		
	}
	
	/**
	 * returns Hibernate session
	 * @return
	 */
	 private Session getSession () {
		 return sessionFactory.getCurrentSession();
	 }
	
	/* 
	 * selects one sale by Id
	 * @param id
	 * @return sale
	 */
	 @Transactional(readOnly = true)
	public Sale selectById(int id) {
		Sale sale = (Sale) getSession().get(Sale.class, id);
	    return sale;
	}

	/*
	 * retrieves all sales from db
	 * @return List of sales
	 */
	 @Transactional(readOnly = true)
	public List<Sale> selectAll() {
	 
	    List<Sale> sales = getSession().createQuery("from sale").list();
	    return sales;
	}
	
	/*
	 * retrieves all sale from db
	 * @return List of sale
	 */
	 @Transactional(readOnly = true)
	public int selectAllCount() {
	    List<Sale> sales = getSession().createQuery("from sale").list();
	    return sales.size();
	}

	/*
	 * inserts a new sale in database
	 * retrieves generated id and sets to sale instance
	 * @param new sale
	 */
	 @Transactional
	public void insert(Sale sale) {
	    Integer id = (Integer) getSession().save(sale);
	    sale.setId(id);           
	}

	/*
	 * updates sale
	 * @param sale to update
	 */
	 @Transactional
	public void update(Sale sale) {
		getSession().merge(sale);
	}

	/*
	 * delete given sale
	 * @param department to sale
	 */
	 @Transactional
	public void delete(Sale sale) {
		getSession().delete(sale);
	}

	 @Transactional
	public void saveOrUpdate(Sale sale) {

		getSession().saveOrUpdate(sale);
		
	}

	 /**
	  * deletes using id
	  */
	 @Transactional
	public void deleteById(int id) {
		 Sale sale = (Sale) getSession().load(Sale.class,id);
		 getSession().delete(sale);
	}

	 /**
	  * performs search operation
	  */
	 @Transactional(readOnly = true)
	public List<Sale> search(String name) {
		   Query query = getSession().createQuery("from sale s where s.name like :name");
         query.setParameter("name", "%"+name+"%");
         
         List<Sale> sales = query.list();
		
         return sales;
	}
}
